<template>
    <el-card class="add-friend-container">
        <el-input v-model="searchQuery" placeholder="搜索用户" class="search-input" />
        <el-button type="primary" @click="searchUsers">搜索</el-button>

        <el-table :data="searchResults" style="width: 100%; margin-top: 20px">
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                    <span v-show="row.status == 'accepted'">已添加</span>
                    <span v-show="row.status == 'pending'">等待接受请求</span>
                    <span v-show="row.status == 'none'">未添加</span>

                </template>
            </el-table-column>
            <el-table-column label="Actions">
                <template #default="{ row }">
                    <el-button type="success" @click="addFriendShip(row)"
                        :disabled="row.status == 'accepted' || row.status == 'pending'">添加朋友</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
</template>

<script lang="ts" setup>
import { onMounted, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { addFriend, searchUsersWithStatus } from '@/service/user/friendShipService';
// 搜素参数
const searchQuery = ref('');
// 搜素结果
const searchResults:any = ref([]);
const loading = ref(false);
const userId: any = ref(localStorage.getItem("userId"));
const searchUsers = async () => {
    if (!searchQuery.value) {
        ElMessage.warning('Please enter a search query.');
        return;
    }
    try {
        console.log("search")
        loading.value = true;
        searchUsersWithStatus(searchQuery.value, userId.value).then(response => {
            searchResults.value = [...response.data];
            loading.value = false;
        })

    } catch (error) {
        loading.value = false;
        ElMessage.error('Failed to search for users.');
    }
};
// 添加好友
const addFriendShip = async (user: any) => {
    try {
        console.log("params" + user.userId + userId.value);
        const res = await addFriend(
            {
                requesterId: userId?.value.toString(),
                receiverId: user.userId.toString()
            });
        if (res && res.status == 200) {
            ElMessage.success('添加好友成功');

            await nextTick(()=>{
            // 重新获取列表
            searchUsers()
            });
        }
    } catch (error) {
        ElMessage.error('添加好友失败');
    }
};
</script>

<style lang="less" scoped>
.add-friend-container {
    .search-input {
        width: 300px;
        margin-right: 10px;
    }
}
</style>